<template>
	<div class="container add_edit">
		<el-form :model="form" :rules="rules" ref="ruleForm" label-width="120px">
			<el-form-item v-if="!form._id" label="小程序名称" ref="name">
				<el-input v-model="form.name" placeholder="请输入小程序名称" clearable></el-input>
			</el-form-item>
			<el-form-item v-if="!form._id"  label="开户电话">
				<el-input v-model="form.phone" placeholder="请输入开户电话" clearable></el-input>
			</el-form-item>  
			<el-form-item  label="主体名称">
				<el-input v-model="form.gs_name" placeholder="请输入主体名称" clearable></el-input>
			</el-form-item>
			<el-form-item   label="支付宝账号">
				<el-input v-model="form.alipay_account" placeholder="请输入支付宝账号" clearable></el-input>
			</el-form-item>
			<el-form-item v-if="form._id" label="备注" ref="remark">
				<el-input v-model="form.remark" placeholder="请输入备注" clearable></el-input>
			</el-form-item>
			<el-form-item>
				<el-button :loading="formLoading" round icon="el-icon-check" class="confirm-btn"
					@click="submitForm('ruleForm')">提交</el-button>
				<el-button round icon="el-icon-back" class="return-btn" @click="returnPage">返回</el-button>
			</el-form-item>
		</el-form>
	</div>
</template>

<script>
	const __name = 'wmz-entitlement-applet';
	export default {
		data() {
			return {
				dataId: '',
				formLoading: false,
				form: {
					name: '',
					alipay_account:'',
					gs_name:"",
					state: '禁用'
				},
				rules: {}
			};
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
		},
		methods: { 
			async loadData() {
				if(this.dataId){
					this.$db[__name].tofirst({
						_id:this.dataId
					}).then(res => {
						if (res.code == 200) {
							this.form=res.datas
						}
					}).catch(() => {
					})
				}
			},
			submitForm(formName) {
				this.$refs[formName].validate((valid, obj) => {
					// 默认获取第一个未验证 form 属性名
					this.$api.set_unvalidated_form_focus(this, obj);
					if (valid) {
						this.formLoading = true;
						if (!this.dataId) {
							this.$db[__name].add(this.form).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						} else {
							this.$db[__name].update(this.dataId, {
								alipay_account:this.form.alipay_account,
								gs_name:this.form.gs_name,
								remark:this.form.remark
							}).then(res => {
								if (res.code == 200) {
									this.getOpenerEventChannel().emit('loadData');
									this.returnPage();
								}
								this.formLoading = false;
							}).catch(() => {
								this.formLoading = false;
							})
						}
					}
				});
			},
			returnPage() {
				uni.$emit('closeTab');
				uni.redirectTo({
					url: '/pages/entitlement/applet'
				});
			}
		},
		created() {
			this.dataId = this.$route.query.id || '';
			this.loadData();
		}
	};
</script>

<style></style>